package com.oa.matter.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.err.BizException;
import com.mdp.core.service.BaseService;
import com.mdp.core.service.SequenceService;
import com.mdp.core.utils.BaseUtils;
import com.oa.matter.entity.MatterInfo;
import com.oa.matter.entity.MatterInspectContent;
import com.oa.matter.entity.MatterInspectItem;
import com.oa.matter.entity.MatterInspectStandard;
import com.oa.matter.mapper.MatterInfoMapper;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@Service
public class MatterInfoService extends BaseService<MatterInfoMapper, MatterInfo> {
    static Logger logger = LoggerFactory.getLogger(MatterInfoService.class);

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }

    /**
     * 请在此类添加自定义函数
     */
    @Autowired
    private SequenceService seqService;

    @Autowired
    private MatterInspectItemService matterInspectItemService;

    @Autowired
    private MatterInspectContentService matterInspectContentService;

    @Autowired
    private MatterInspectStandardService matterInspectStandardService;

    public Map<String, Object> parseExcel(InputStream fis) {
        Map<String, Object> map = new HashMap();
        try {
            HSSFWorkbook book = new HSSFWorkbook(fis); // 工作簿
            HSSFSheet sheet = book.getSheetAt(0); // 工作表
            int firstRow = sheet.getFirstRowNum(); // 第一行下标 0
            int lastRow = sheet.getLastRowNum(); // 最后一行下标

//			HSSFRow row = sheet.getRow(firstRow);//第一行第9列
//			HSSFCell cell = row.getCell(9);
//			String stringCellValue = cell.getStringCellValue();
//			System.out.println(stringCellValue);
//
//			HSSFRow row1 = sheet.getRow(firstRow+1);//第一行第9列
//			HSSFCell cell1 = row1.getCell(9);
//			String stringCellValue1 = cell1.getStringCellValue();
//			System.out.println(stringCellValue1);

            List<Map<String, Object>> infoList = new ArrayList<>();//基本信息
            List<Map<String, Object>> inspectContentList = new ArrayList<>();//检查内容
            List<Map<String, Object>> inspectItemList = new ArrayList<>();//检查项目
            List<Map<String, Object>> inspectStandardList = new ArrayList<>();//检查标准
            if (lastRow > 2) {//表头占2行
                Map<Integer, String> excelHead = getExcelHead(sheet);
                int firstCell = sheet.getRow(firstRow).getFirstCellNum(); // 第一列 // 0
                int lastCell = sheet.getRow(firstRow).getLastCellNum(); // 最后一列14

                String infoId = new String();
                String itemId = new String();
                String contentId = new String();
                for (int i = firstRow + 2; i < lastRow; i++) {//从第三行开始遍历拿数据

                    HSSFRow row = sheet.getRow(i); // 工作表的行
                    if (row != null) {
                        for (int j = firstCell; j < lastCell; j++) {
                            HSSFCell cell = row.getCell(j);
                            String val = new String(); // 值
                            try {
                                if (cell != null) {
                                    cell.setCellType(CellType.STRING);
                                    val = cell.getStringCellValue(); // 值
                                }
                            } catch (Exception e) {
                                logger.error(String.valueOf(e));
                                logger.error("第" + (i + 1) + "行，第" + (j + 1) + "列,列名" + excelHead.get(j) + "格式错误，必须是文本格式，");
                                throw new BizException("第" + (i + 1) + "行，第" + (j + 1) + "列,列名" + excelHead.get(j) + "格式错误，必须是文本格式，");
                            }
                            val = (val == null ? "" : val.trim());

                            Map<String, Object> infoMap = new HashMap<>();
                            Map<String, Object> inspectItemMap = new HashMap<>();
                            Map<String, Object> inspectContentMap = new HashMap<>();
                            Map<String, Object> inspectStandardMap = new HashMap<>();
                            //基本信息
                            //基本信息(前3列)
                            if (j == 1 && !StringUtils.isEmpty(val)) {
                                infoMap.put("id", seqService.getTablePK("matter_info", "id"));
                                infoId = (String) infoMap.get("id");
                                infoMap.put("majorName", row.getCell(j - 1).getStringCellValue());
                                infoMap.put("businessName", val);
                                infoMap.put("companyHandbook", row.getCell(j + 1).getStringCellValue());
                                infoList.add(infoMap);
                            } else if (j == 4 && !StringUtils.isEmpty(val)) {
                                //检查项目
                                //(4-5列)
                                inspectItemMap.put("id", seqService.getTablePK("matter_inspect_item", "id"));
                                itemId = (String) inspectItemMap.get("id");
                                HSSFCell cc = row.getCell(j - 1);
                                cc.setCellType(CellType.STRING);
                                inspectItemMap.put("orderNumber", cc.getStringCellValue());
                                inspectItemMap.put("name", val);
                                inspectItemMap.put("infoId", infoId);
                                inspectItemList.add(inspectItemMap);

                            } else if (j == 5 && !StringUtils.isEmpty(val)) {
                                //检查内容
                                inspectContentMap.put("id", seqService.getTablePK("matter_inspect_content", "id"));
                                contentId = (String) inspectContentMap.get("id");
                                inspectContentMap.put("serialNumber", val);
                                inspectContentMap.put("contentName", row.getCell(6).getStringCellValue());
                                inspectContentMap.put("inspectMethod", row.getCell(7).getStringCellValue());
                                inspectContentMap.put("legalFrequency", row.getCell(11).getStringCellValue());
                                inspectContentMap.put("adviseFrequency", row.getCell(12).getStringCellValue());
                                inspectContentMap.put("remarks", row.getCell(13).getStringCellValue());
                                inspectContentMap.put("itemId", itemId);
                                inspectContentList.add(inspectContentMap);

                            } else if (j == 8 && !StringUtils.isEmpty(val)) {
                                //检查标准
                                inspectStandardMap.put("id", seqService.getTablePK("matter_inspect_standard", "id"));
                                inspectStandardMap.put("standard", val);
                                inspectStandardMap.put("accordingName", row.getCell(9).getStringCellValue());
                                HSSFCell clauseCell = row.getCell(10);
                                clauseCell.setCellType(CellType.STRING);
                                inspectStandardMap.put("clause", clauseCell.getStringCellValue());
                                inspectStandardMap.put("contentId", contentId);
                                inspectStandardList.add(inspectStandardMap);

                            }

                        }

                    }
                }
                map.put("infoList", infoList);
                map.put("inspectItemList", inspectItemList);
                map.put("inspectContentList", inspectContentList);
                map.put("inspectStandardList", inspectStandardList);

            } else {
                throw new BizException("模板没有数据！");
            }
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            throw new BizException(e.getMessage());
        }
        return map;
    }

    public static Map<Integer, String> getExcelHead(HSSFSheet sheet) {
        Map<String, String> map = new HashMap<>();// 中英文对应关系
        Map<Integer, String> map2 = new HashMap<>();// 索引 英文
        Map<String, Integer> map3 = new HashMap<>();// 中文 索引

        map.put("专业名称", "majorName");
        map.put("业务名称", "businessName");
        map.put("公司手册", "companyHandbook");
        map.put("序号", "orderNumber");
        map.put("检查项目", "name");
        map.put("编号", "serialNumber");
        map.put("检查内容", "contentName");
        map.put("检查方法", "inspectMethod");
        map.put("检查标准", "standard");
        map.put("依据名称", "accordingName");
        map.put("依据条款", "clause");
        map.put("法定频次", "legalFrequency");
        map.put("建议频次", "adviseFrequency");
        map.put("备注", "remarks");

        int firstCell = sheet.getRow(0).getFirstCellNum(); // 第一行第一列 0
        int lastCell = sheet.getRow(0).getLastCellNum(); // 最后一列32

        for (int j = firstCell; j < lastCell; j++) {
            HSSFCell cell2 = sheet.getRow(0).getCell(j);
            String key = cell2.getStringCellValue(); // 字段
            //System.out.println(key);
            if (j >= 9 && j <= 12) {
                cell2 = sheet.getRow(1).getCell(j);
                key = cell2.getStringCellValue(); // 字段
                //System.out.println(key);
            }
            map3.put(key, j);
            map2.put(j, map.get(key));
        }
        return map2;
    }

    /**
     * 导入数据到数据库
     */
    @Transactional
    public void importData(Map<String, Object> map) {
        List<Map<String, Object>> infoList = (List<Map<String, Object>>) map.get("infoList");
        List<Map<String, Object>> inspectItemList = (List<Map<String, Object>>) map.get("inspectItemList");
        List<Map<String, Object>> inspectContentList = (List<Map<String, Object>>) map.get("inspectContentList");
        List<Map<String, Object>> inspectStandardList = (List<Map<String, Object>>) map.get("inspectStandardList");
        if (infoList != null && infoList.size() > 0) {
//            this.batchInsert("com.qqkj.mk.sxk.entity.matter.MatterInfo.insert", infoList);
            for (Map<String, Object> objectMap : infoList) {
                baseMapper.insert(BaseUtils.fromMap(objectMap, MatterInfo.class));
            }
        }

        if (inspectItemList != null && inspectItemList.size() > 0) {
//            matterInspectItemService.batchInsert("com.qqkj.mk.sxk.entity.matter.MatterInspectItem.insert", inspectItemList);
            for (Map<String, Object> objectMap : inspectItemList) {
                matterInspectItemService.insert(BaseUtils.fromMap(objectMap, MatterInspectItem.class));
            }
        }

        if (inspectContentList != null && inspectContentList.size() > 0) {
//            matterInspectContentService.batchInsert("com.qqkj.mk.sxk.entity.matter.MatterInspectContent.insert", inspectContentList);
            for (Map<String, Object> objectMap : inspectContentList) {
                matterInspectContentService.insert(BaseUtils.fromMap(objectMap, MatterInspectContent.class));
            }
        }

        if (inspectStandardList != null && inspectStandardList.size() > 0) {
//            matterInspectStandardService.batchInsert("com.qqkj.mk.sxk.entity.matter.MatterInspectStandard.insert", inspectStandardList);
            for (Map<String, Object> objectMap : inspectStandardList) {
                matterInspectStandardService.insert(BaseUtils.fromMap(objectMap, MatterInspectStandard.class));
            }
        }
    }

    /**
     * 根据id获取事项的信息
     *
     * @return
     */
    public Map<String, Object> getMatterInfo(IPage page, QueryWrapper ew, String matterInfoId) {
        Map<String, Object> map = new HashMap<>();

        MatterInfo matterInfo = new MatterInfo();
        matterInfo.setId(matterInfoId);
        MatterInfo selectOneObject = this.selectOneObject(matterInfo);
        map.put("matterInfo", selectOneObject);

        List<Map<String, Object>> itemList = new ArrayList<>();
        itemList = matterInspectItemService.selectListMapByWhere(page, ew, map("infoId", matterInfoId));
        map.put("itemList", itemList);

        List<Map<String, Object>> contentList = new ArrayList<>();
        List<Map<String, Object>> standardList = new ArrayList<>();
        if (itemList.size() > 0) {
            contentList = matterInspectContentService.selectListMapByWhere(page, ew, map((String) itemList.get(0).get("id")));
            if (contentList.size() > 0) {
                standardList = matterInspectStandardService.selectListMapByWhere(page, ew, map((String) contentList.get(0).get("id")));
            }
        }
        map.put("contentList", contentList);
        map.put("standardList", standardList);

        return map;

    }
}

